package org.example.rabbitmq.consumer.notify;

import com.rabbitmq.client.Channel;
import org.example.rabbitmq.consumer.mq.RabbitMqManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;

public class DynamicQueueCreatedConsumer implements ChannelAwareMessageListener {
    Logger logger = LoggerFactory.getLogger(DynamicQueueCreatedConsumer.class);

    @Autowired
    RabbitMqManager rabbitMqManager;

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        String queueName = new String(message.getBody());
        logger.info("receive queue created event, queue: " + queueName);
        boolean created = rabbitMqManager.createQueueContainerIfAbsent(queueName);
        if (created) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            logger.info("queue listen container created, queue: " + queueName);
        } else {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            logger.error("create queue listen container failed");
        }
    }
}